package com.miqtech.master.wyrecorder.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.miqtech.master.wyrecorder.constants.API;
import com.miqtech.master.wyrecorder.entity.User;
import com.miqtech.master.wyrecorder.user.UserProxy;

/**
 * Created by 123 on 2017/4/11.
 */
public class LogCatHelper {
	private static final String TAG = "LogCatHelper";
    private static LogCatHelper instance = null;
    private String dirPath;//保存路径
    private int appid;//应用pid
    private Thread logThread;
    static private File logFile;

    /**
     * @param mContext
     * @return
     */
    public static LogCatHelper getInstance(Context mContext){
        if(instance == null){
            instance = new LogCatHelper(mContext);
        }
        return instance;
    }

    private LogCatHelper(Context mContext) {
        appid = android.os.Process.myPid();
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            //dirPath = mContext.getExternalCacheDir().getPath() + File.separator + "直播日志";
            dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "yuer";
        } else {
            dirPath = mContext.getCacheDir().getPath() + "直播日志";
        }
		Log.e("LogCatHelper","brand = "+ DeviceUtils.getPhoneBrand() + " BuildVersion = " + DeviceUtils.getBuildVersion() + " Modle = " + DeviceUtils.getPhoneModel());
        File dir = new File(dirPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
    }

    /**
     * 启动log日志保存
     */
    public void start(){
        if(logThread != null){
			stop();
		}
        logThread = new Thread(new LogRunnable(appid, dirPath));
        if(logThread  != null){
			logThread.start();
		}
    }
    public void stop(){
		Log.e(TAG, "stop()");
        if(logThread != null){
			logThread.interrupt();
			try {
				logThread.join();
			} catch (InterruptedException ie) {
				logThread.interrupt();
			}
			logThread = null;
        }
		Log.e(TAG, "stop ok");
    }

    public void uploadLogFile(){
		User user = UserProxy.getUser();
        final HashMap<String, String> params = new HashMap<>();
		params.clear();
        params.put("userId", user.getId());
        params.put("token", user.getToken());

		final Map<String, String> fileParams = new HashMap<>();
        fileParams.put("log", logFile.getAbsolutePath());
        new Thread(new Runnable() {
            @Override
            public void run() {
                FileUploadUtil.uploadFile(API.HOST + API.UPLOAD_FIle, params, fileParams, mHandler);
            }
        }).start();

    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case FileUploadUtil.SUCCESS:
					Log.e(TAG, "upload success");
                    break;
                case FileUploadUtil.FAILED:
					Log.e(TAG, "upload failed");
                    break;
            }
        }
    };

    private static class LogRunnable implements Runnable{

        private Process mProcess;
        private FileOutputStream fos;
        private BufferedReader mReader;
        private String cmds;
        private String mPid;

        public LogRunnable(int pid,String dirPath) {
            this.mPid = ""+pid;
            try {
                logFile = new File(dirPath,"yuerlog"+".txt");
                if(logFile.exists()){
                    logFile.delete();
                }
                logFile.createNewFile();
                fos = new FileOutputStream(logFile,true);
            } catch (Exception e) {
                e.printStackTrace();
            }
            cmds = "logcat *:e | grep \"(" + mPid + ")\"";
        }

        @Override
        public void run() {
            try {
                mProcess = Runtime.getRuntime().exec(cmds);
                mReader = new BufferedReader(new InputStreamReader(mProcess.getInputStream()),1024);
                String line;
                while(((line = mReader.readLine()) != null) && (!Thread.interrupted())){
                    if(line.length() == 0){
                        continue;
                    }
                    if(fos != null && line.contains(mPid)){
                        fos.write((FormatDate.getFormatTime()+" "+line+"\r\n").getBytes());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                if(mProcess != null){
                    mProcess.destroy();
                    mProcess = null;
                }
                try {
                    if(mReader != null){
                        mReader.close();
                        mReader = null;
                    }
                    if(fos != null){
                        fos.close();
                        fos = null;
                    }
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }
    }

    @SuppressLint("SimpleDateFormat")
    private static class FormatDate{

        public static String getFormatDate(){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
            return sdf.format(System.currentTimeMillis());
        }

        public static String getFormatTime(){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.format(System.currentTimeMillis());
        }
    }
}
